const MessageManager = {
    pendingMessages: new Map(),
    retryCount: 3,
    retryInterval: 2000, // 2秒重试间隔
    currentPage: 0,
    pageSize: 12,
    hasMoreMessages: true,
    isLoadingMessages: false,

    sendMessage(message) {
        // 生成消息ID
        message.messageId = this.generateMessageId();
        message.timestamp = Date.now();
        message.status = 'SENDING';
        message.type = 'CHAT';

        // 存储消息到待确认列表
        this.pendingMessages.set(message.messageId, {
            message,
            retries: 0,
            timestamp: Date.now()
        });

        // 发送消息并启动重试机制
        this.doSendMessage(message);
        return message.messageId;
    },

    doSendMessage(message) {
        try {
            WebSocketManager.sendMessage(message);
            this.scheduleRetry(message.messageId);
        } catch (error) {
            console.error('Failed to send message:', error);
            UIManager.updateMessageStatus(message.messageId, 'FAILED');
            this.pendingMessages.delete(message.messageId);
        }
    },

    scheduleRetry(messageId) {
        const pendingMessage = this.pendingMessages.get(messageId);
        if (!pendingMessage) return;

        pendingMessage.retryTimer = setTimeout(() => {
            const message = this.pendingMessages.get(messageId);
            if (message && message.retries < this.retryCount) {
                message.retries++;
                console.log(`Retrying message ${messageId}, attempt ${message.retries}`);
                this.doSendMessage(message.message);
            } else if (message) {
                console.error(`Message ${messageId} failed after ${this.retryCount} retries`);
                UIManager.updateMessageStatus(messageId, 'FAILED');
                this.pendingMessages.delete(messageId);
            }
        }, this.retryInterval);
    },

    confirmMessage(messageId) {
        const pendingMessage = this.pendingMessages.get(messageId);
        if (pendingMessage && pendingMessage.retryTimer) {
            clearTimeout(pendingMessage.retryTimer);
        }
        this.pendingMessages.delete(messageId);
    },

    generateMessageId() {
        return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    },

    async loadChatHistory(user1, user2, loadMore = false) {
        if (this.isLoadingMessages || (!loadMore && !this.hasMoreMessages)) {
            return;
        }

        try {
            this.isLoadingMessages = true;
            if (!loadMore) {
                this.currentPage = 0;
                this.hasMoreMessages = true;
                UIManager.clearMessages();
            }

            const response = await fetch(
                `/api/chat/history?user1=${encodeURIComponent(user1)}&user2=${encodeURIComponent(user2)}&page=${this.currentPage}&size=${this.pageSize}`
            );

            if (!response.ok) {
                throw new Error('Failed to load chat history');
            }

            const messages = await response.json();
            
            // 如果消息数量小于页大小，说明没有更多消息了
            if (messages.length < this.pageSize) {
                this.hasMoreMessages = false;
            }

            // 显示消息
            messages.reverse().forEach(message => {
                const isSent = message.from === UserManager.currentUser;
                UIManager.addHistoricalMessage(message, isSent);
            });

            // 如果是首次加载，滚动到底部
            if (!loadMore) {
                UIManager.scrollToBottom();
            }

            this.currentPage++;
        } catch (error) {
            console.error('Error loading chat history:', error);
            UIManager.showSystemMessage('Failed to load chat history');
        } finally {
            this.isLoadingMessages = false;
        }
    }
}; 